package org.aplombh.java.awcing.basic.graph.shortestPath.dijkstra;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 给定一个 n 个点 m 条边的有向图，图中可能存在重边和自环，所有边权均为正值=
 * <p>
 * 请你求出 1 号点到 n 号点的最短距离，如果无法从 1 号点走到 n 号点，则输出 −1=
 * <p>
 * 输入格式
 * 第一行包含整数 n 和 m=
 * <p>
 * 接下来 m 行每行包含三个整数 x,y,z，表示存在一条从点 x 到点 y 的有向边，边长为 z=
 * <p>
 * 输出格式
 * 输出一个整数，表示 1 号点到 n 号点的最短距离=
 * <p>
 * 如果路径不存在，则输出 −1=
 * <p>
 * 数据范围
 * 1≤n≤500,
 * 1≤m≤105 ,
 * 图中涉及边长均不超过10000=
 * <p>
 * 输入样例：
 * 3 3
 * 1 2 2
 * 2 3 1
 * 1 3 4
 * 输出样例：
 * 3
 */
public class Dijkstra_849 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        Dijkstra dijkstra = new Dijkstra(n);
        while (m-- != 0) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            int c = scanner.nextInt();
            dijkstra.g[a][b] = Math.min(dijkstra.g[a][b], c);
        }

        System.out.println(dijkstra.dijkstra());
    }
}

class Dijkstra {
    public static final int N = 510;
    int[][] g = new int[N][N]; // 邻接矩阵存储图 Store the graph
    int[] dist = new int[N]; // 到某点的最短距离 The distance to some point
    boolean[] st = new boolean[N]; // 是否访问过  visited
    int n;

    Dijkstra(int n) {
        init(n);
    }

    void init(int n) {
        this.n = n;
        // 初始化 initialize
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == j) g[i][j] = 0;
                else g[i][j] = 1 << 30;
            }
        }
        Arrays.fill(dist, 1 << 30);
        dist[1] = 0;
    }

    public int dijkstra() {
        // 进行n次循环，每次找到未访问的距离最短的一个点 Do n loops, each time finding the point with the shortest unvisited distance
        for (int i = 0; i < n; i++) {
            // 最短边连接的点 The point at which the shortest edge is connected
            int t = -1;
            // 找到最短的那条边连接的点 Find the point where the shortest edge connects
            for (int j = 1; j <= n; j++) {
                // 如果当前点未访问过并且它的最短路径比dist[t]短，则给t赋值为当前点 If the current point is unvisited and its shortest path is shorter than dist[t], then t is assigned to the current point
                if (!st[j] && (t == -1 || dist[t] > dist[j]))
                    t = j;
            }
            // 标记已访问 Mark accessed
            st[t] = true;

            // 经过当前点，是否可以更新别的点的最短距离 Passing the current point, can update the shortest distance of other points
            for (int j = 1; j <= n; j++) {
                dist[j] = Math.min(dist[j], dist[t] + g[t][j]);
            }
        }
        if (dist[n] == 1 << 30) return -1;
        return dist[n];
    }
}